package com.tdwyz.fictionmanage.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tdwyz.fictionmanage.mapper.ChapterMapper;
import com.tdwyz.fictionmanage.pojo.Chapter;
import com.tdwyz.fictionmanage.pojo.PageBean;
import com.tdwyz.fictionmanage.pojo.Result;
import com.tdwyz.fictionmanage.pojo.SensitiveWord;
import com.tdwyz.fictionmanage.utils.SensitiveWordUtil;
import com.tdwyz.fictionmanage.utils.ThreadLocalUtil;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 14543
 * @version 1.0
 * @description: TODO
 * @date 2024/7/28 16:06
 */

@Service
public class ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private SensitiveWordService sensitiveWordService;

    /**
     * 新增小说章节
     * @param chapter
     */
    public boolean insert(Chapter chapter) {
        Integer userId = ThreadLocalUtil.getUserId();
        chapter.setCreateUser(userId);

        return chapterMapper.insert(chapter);
    }

    /**
     * 展示某小说的全部章节（分页显示）
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageBean<Chapter> list(Integer pageNum, Integer pageSize) {
        //1. 返回对象
        PageBean<Chapter> pageBean = new PageBean<>();

        //2.  开启分页
        PageHelper.startPage(pageNum,pageSize);

        //3. 归属问题
        Integer userId = ThreadLocalUtil.getUserId();
        List<Chapter> articles= chapterMapper.list(userId);

        //使用page
        Page<Chapter> page= (Page<Chapter>) articles;

        //填充数据
        pageBean.setTotal(page.getTotal());
        pageBean.setData(page.getResult());

        return pageBean;
    }

    /**
     * 获取文章详情（用户数据回显）
     * @param id
     * @return
     */
    public Chapter getById(Integer id) {
        return chapterMapper.getById(id);
    }

    /**
     * 修改小说某章节内容
     * @param chapter
     * @return
     */
    public boolean update(Chapter chapter) {
        //审核内容
        handlerSensitiveWordScan(chapter);
        //调用数据层插入数据
        return chapterMapper.update(chapter);
    }

    /**
     * 对章节的标题进行敏感词汇审核
     * @param chapter
     */
    private void handlerSensitiveWordScan(Chapter chapter){
        //获取词典
        //从数据库中获取所有的敏感词汇
        List<SensitiveWord> sensitiveWords = sensitiveWordService.list();

        //初始化词库
        SensitiveWordUtil.initMap(sensitiveWords.stream().map(SensitiveWord::getWord).collect(Collectors.toList()));

        //匹配文章和标题违禁词汇
        if (SensitiveWordUtil.matchWords(chapter.getName()).size()>0) {
            throw new RuntimeException("标题存在违禁词");
        }
    }

    /**
     * 删除章节
     * @param id
     * @return
     */
    public boolean delete(Integer id) {
        return chapterMapper.delete(id);
    }
}
